package com.advertisementsystem.Controller;

import com.advertisementsystem.Exception.BusinessException;
import com.advertisementsystem.Exception.ResponseResult;
import com.advertisementsystem.Servie.BillService;
import com.advertisementsystem.entity.PaymentOrder;
import com.advertisementsystem.vo.BillPaymentQRCodeVO;
import com.advertisementsystem.vo.BillPaymentStatusVO;
import com.advertisementsystem.vo.BillVO;
import com.advertisementsystem.vo.PaymentRequestVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/bills")
@Slf4j
public class BillController {

    @Autowired
    private BillService billService;



    private static final Map<String, PaymentOrder> paymentOrders = new ConcurrentHashMap<>();
    /**
     * 获取账单列表
     *
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @param status 账单状态
     * @param keyword 搜索关键词
     * @return 账单列表
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('ADMIN', 'ADVERTISER', 'DEVICE_OWNER')")
    public ResponseResult<IPage<BillVO>> getBills(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword) {
        try {

            IPage<BillVO> bills = billService.getBills(pageNum, pageSize, status, keyword);
            return ResponseResult.success(bills);
        } catch (Exception e) {
            log.error("获取账单列表失败", e);
            return ResponseResult.error("获取账单列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取账单详情
     *
     * @param id 账单ID
     * @return 账单详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN', 'ADVERTISER', 'DEVICE_OWNER')")
    public ResponseResult<BillVO> getBillDetail(@PathVariable Long id) {
        try {
            BillVO bill = billService.getBillDetail(id);
            return ResponseResult.success(bill);
        } catch (BusinessException e) {
            log.error("获取账单详情失败: {}", e.getMessage());
            return ResponseResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取账单详情失败", e);
            return ResponseResult.error("获取账单详情失败");
        }
    }

    @PostMapping("/payment/qrcode")
    @PreAuthorize("hasAnyRole('ADVERTISER')")
    public ResponseResult<BillPaymentQRCodeVO> generatePaymentQRCode(@RequestBody PaymentRequestVO request) {
        try {
            log.info("生成支付二维码请求: {}", request);

            // 检查请求参数
            if (request.getBillId() == null) {
                return ResponseResult.error("账单ID不能为空");
            }

            if (request.getPaymentMethod() == null) {
                return ResponseResult.error("支付方式不能为空");
            }

            // 获取账单信息
            BillVO bill = billService.getBillDetail(request.getBillId());
            if (bill == null) {
                return ResponseResult.error("账单不存在");
            }

            // 检查账单状态
            if ("PAID".equals(bill.getStatus())) {
                return ResponseResult.error("账单已支付，无需重复支付");
            }

            // 生成支付订单号
            String paymentOrderId = "PAY" + System.currentTimeMillis() + "_" + request.getBillId();

            // 生成支付二维码
            String qrCodeUrl;
            if ("WECHAT".equals(request.getPaymentMethod())) {
                qrCodeUrl = generateWechatPayQRCode(paymentOrderId, bill.getAmount().toString());
            } else if ("ALIPAY".equals(request.getPaymentMethod())) {
                qrCodeUrl = generateAlipayQRCode(paymentOrderId, bill.getAmount().toString());
            } else {
                return ResponseResult.error("不支持的支付方式");
            }

            // 创建支付订单记录
            PaymentOrder paymentOrder = new PaymentOrder();
            paymentOrder.setPaymentOrderId(paymentOrderId);
            paymentOrder.setBillId(request.getBillId());
            paymentOrder.setAmount(bill.getAmount());
            paymentOrder.setPaymentMethod(request.getPaymentMethod());
            paymentOrder.setStatus("PENDING");
            paymentOrder.setCreateTime(System.currentTimeMillis());
            paymentOrder.setExpireTime(System.currentTimeMillis() + 30 * 60 * 1000); // 30分钟有效期

            // 保存支付订单
            paymentOrders.put(paymentOrderId, paymentOrder);

            // 返回支付二维码信息
            BillPaymentQRCodeVO result = new BillPaymentQRCodeVO();
            result.setQrCodeUrl(qrCodeUrl);
            result.setPaymentOrderId(paymentOrderId);
            result.setExpireTime(paymentOrder.getExpireTime());

            return ResponseResult.success(result);
        } catch (BusinessException e) {
            log.error("生成支付二维码失败: {}", e.getMessage());
            return ResponseResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("生成支付二维码失败", e);
            return ResponseResult.error("生成支付二维码失败");
        }
    }
    /**
     * 检查支付状态
     */
    @GetMapping("/{id}/payment/status")
    @PreAuthorize("hasAnyRole('ADVERTISER')")
    public ResponseResult<BillPaymentStatusVO> checkPaymentStatus(@PathVariable Long id) {
        try {
            // 获取账单信息
            BillVO bill = billService.getBillDetail(id);
            if (bill == null) {
                return ResponseResult.error("账单不存在");
            }

            BillPaymentStatusVO result = new BillPaymentStatusVO();
            result.setBillId(id);
            result.setStatus(bill.getStatus());

            return ResponseResult.success();
        } catch (BusinessException e) {
            log.error("检查支付状态失败: {}", e.getMessage());
            return ResponseResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("检查支付状态失败", e);
            return ResponseResult.error("检查支付状态失败");
        }
    }
    /**
     * 微信支付回调
     */
    // @PostMapping("/payment/wechat/notify")
    // public String wechatPayNotify(@RequestBody String notifyData) {
    //     log.info("收到微信支付回调通知: {}", notifyData);
    //
    //     try {
    //         // 解析回调数据（实际项目需进行签名验证等安全检查）
    //         String paymentOrderId = parseOrderIdFromWechatNotify(notifyData);
    //
    //         if (paymentOrderId != null) {
    //             // 查找支付订单
    //             PaymentOrder paymentOrder = paymentOrders.get(paymentOrderId);
    //
    //             if (paymentOrder != null && "PENDING".equals(paymentOrder.getStatus())) {
    //                 // 更新支付订单状态
    //                 paymentOrder.setStatus("PAID");
    //                 paymentOrder.setPayTime(System.currentTimeMillis());
    //
    //                 // 更新账单状态
    //                 billService.payBill(paymentOrder.getBillId(), paymentOrder.getPaymentMethod());
    //
    //                 log.info("微信支付成功处理完成，订单ID: {}", paymentOrderId);
    //             }
    //         }
    //
    //         // 返回成功响应（格式符合微信支付要求）
    //         return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    //     } catch (Exception e) {
    //         log.error("处理微信支付回调失败", e);
    //         // 返回失败响应
    //         return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>";
    //     }
    // }

    // @PostMapping("/payment/alipay/notify")
    // public String alipayPayNotify(@RequestBody String notifyData) {
    //     log.info("收到支付宝支付回调通知: {}", notifyData);
    //
    //     try {
    //         // 解析回调数据（实际项目需进行签名验证等安全检查）
    //         String paymentOrderId = parseOrderIdFromAlipayNotify(notifyData);
    //
    //         if (paymentOrderId != null) {
    //             // 查找支付订单
    //             PaymentOrder paymentOrder = paymentOrders.get(paymentOrderId);
    //
    //             if (paymentOrder != null && "PENDING".equals(paymentOrder.getStatus())) {
    //                 // 更新支付订单状态
    //                 paymentOrder.setStatus("PAID");
    //                 paymentOrder.setPayTime(System.currentTimeMillis());
    //
    //                 // 更新账单状态
    //                 billService.payBill(paymentOrder.getBillId(), paymentOrder.getPaymentMethod());
    //
    //                 log.info("支付宝支付成功处理完成，订单ID: {}", paymentOrderId);
    //             }
    //         }
    //
    //         // 返回成功响应（格式符合支付宝要求）
    //         return "success";
    //     } catch (Exception e) {
    //         log.error("处理支付宝支付回调失败", e);
    //         // 返回失败响应
    //         return "fail";
    //     }
    // }
    /**
     * 模拟支付成功（仅用于测试）
     */
    @PostMapping("/{id}/mock-payment")
    @PreAuthorize("hasAnyRole('ADVERTISER')")
    public ResponseResult<Void> mockPaymentSuccess(@PathVariable Long id) {
        try {
            log.info("模拟支付账单: {}", id);

            // 更新账单状态
            billService.payBill(id, "MOCK");

            log.info("模拟支付成功完成");
            return ResponseResult.success();
        } catch (BusinessException e) {
            log.error("模拟支付失败: {}", e.getMessage());
            return ResponseResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("模拟支付失败", e);
            return ResponseResult.error("模拟支付失败");
        }
    }

    // 生成微信支付二维码URL
    private String generateWechatPayQRCode(String orderId, String amount) {
        // 实际项目中应调用微信支付API生成二维码
        // 这里直接使用在线二维码生成服务模拟
        String content = "weixin://wxpay/bizpayurl?pr=" + amount + "&orderno=" + orderId;
        return "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" + content;
    }
    // 生成支付宝支付二维码URL
    private String generateAlipayQRCode(String orderId, String amount) {
        // 实际项目中应调用支付宝API生成二维码
        // 这里直接使用在线二维码生成服务模拟
        String content = "alipays://platformapi/startapp?appId=09999988&orderStr=" + orderId + "_" + amount;
        return "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" + content;
    }

    // 从微信支付回调解析订单号
    private String parseOrderIdFromWechatNotify(String notifyData) {
        // 简化处理，实际项目中需要根据XML格式解析
        if (notifyData.contains("<out_trade_no>") && notifyData.contains("</out_trade_no>")) {
            int start = notifyData.indexOf("<out_trade_no>") + "<out_trade_no>".length();
            int end = notifyData.indexOf("</out_trade_no>");
            return notifyData.substring(start, end);
        }
        return null;
    }

    // 从支付宝回调解析订单号
    private String parseOrderIdFromAlipayNotify(String notifyData) {
        // 简化处理，实际项目中需要根据表单参数解析
        if (notifyData.contains("out_trade_no=")) {
            int start = notifyData.indexOf("out_trade_no=") + "out_trade_no=".length();
            int end = notifyData.indexOf("&", start);
            if (end == -1) {
                end = notifyData.length();
            }
            return notifyData.substring(start, end);
        }
        return null;
    }

}